/**
 * @format
 */

import {useEffect, useRef, useState} from 'react';
import {
  Alert,
  Image,
  StyleSheet,
  Text,
  ToastAndroid,
  TouchableOpacity,
  View,
} from 'react-native';
import {Dimensions} from 'react-native';
import baseRounds from './baseRounds.json';
import hignRounds from './hignRounds.json';
// console.log("baseRounds",baseRounds);

const {width: swidth, height: sheight} = Dimensions.get('window');
let cardHeight = sheight / 3.5;
let cardWidth = (cardHeight * 677) / 1043;
export default () => {
  const totalRound = Object.keys(baseRounds).length;
  const cutdownTotal = 80;
  const seconds = useRef();

  const [round, setRound] = useState(0);
  const [bigRound, setBigRound] = useState(1);

  const [nowBigRound, setNowBigRound] = useState(baseRounds['1']);
  const [nowRound, setNowRound] = useState(baseRounds['1'][0]);

  const [list, setList] = useState([
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
  ]);
  const [allCards, setAllCards] = useState([
    {
      num: 1,
      image: require('./images/24/1.jpg'),
    },
    {
      num: 2,
      image: require('./images/24/2.jpg'),
    },
    {
      num: 3,
      image: require('./images/24/3.jpg'),
    },
    {
      num: 4,
      image: require('./images/24/4.jpg'),
    },
    {
      num: 5,
      image: require('./images/24/5.jpg'),
    },
    {
      num: 6,
      image: require('./images/24/6.jpg'),
    },
    {
      num: 7,
      image: require('./images/24/7.jpg'),
    },
    {
      num: 8,
      image: require('./images/24/8.jpg'),
    },
    {
      num: 9,
      image: require('./images/24/9.jpg'),
    },
    {
      num: 10,
      image: require('./images/24/10.jpg'),
    },
    {
      num: 11,
      image: require('./images/24/11.jpg'),
    },
    {
      num: 12,
      image: require('./images/24/12.jpg'),
    },
    {
      num: 13,
      image: require('./images/24/13.jpg'),
    },
  ]);
  const [cards, setCards] = useState([]);
  console.log('swidth==', swidth, sheight);
  const timerRef = useRef(null);
  // 使用useState来存储倒计时的数值，初始值为10
  const [count, setCount] = useState(cutdownTotal);

  useEffect(() => {
    init(round);
  }, []);
  const init = roundIndex => {
    let rs = getElements(roundIndex);
    setRound(roundIndex);
    setCards(rs);
    setList(list.map(item => null));
  };
  useEffect(() => {
    setCount(cutdownTotal);
    // 使用setInterval创建一个定时器
    // 这个定时器每隔1000毫秒（1秒）执行一次回调函数
    timerRef.current = setInterval(() => {
      // 在回调函数里，更新倒计时的数值

      setCount(prevCount => {
        if (prevCount <= 1) {
          clearInterval(timerRef.current);
          clear();
          return 0;
        } else {
          return prevCount - 1;
        }
      });
    }, 1000);

    // 返回一个清理函数，用于在组件卸载或依赖项变化时清除定时器
    return () => {
      if (timerRef.current) {
        // 清除定时器
        clearInterval(timerRef.current);
      }
    };
  }, [round]);

  const getElements = roundIndex => {
    return nowBigRound[roundIndex].nums.map(item => {
      return allCards[item - 1];
    }); // 取前 count 个元素
  };

  const clickCard = (item, index) => {
    let findNullIndex = list.findIndex(it => it === null);
    if (findNullIndex !== -1) {
      list[findNullIndex] = item;
      setList([...list]);
      cards[index] = null;
      setCards([...cards]);
    }
  };

  const addOp = op => {
    let findNullIndex = list.findIndex(it => it === null);
    if (findNullIndex !== -1) {
      list[findNullIndex] = op;
      setList([...list]);
    }
  };

  const nextRound = () => {
    setRound(round + 1);
    init(round + 1);
  };

  // 计算值
  const computeValue = () => {
    let strs = list
      .map(item => {
        if (typeof item === 'string') {
          return item;
        } else if (item !== null) {
          return item.num;
        }
        return '';
      })
      .join('');
    console.log('strs', strs);
    let value = eval(strs);
    if (value === 24) {
      console.log('success', value);
    } else {
      ToastAndroid.show('结果不正确', 1);
    }
    console.log('value', value);
  };

  const submit = () => {
    computeValue();
  };

  const clear = () => {
    let cs = list.filter(item => item && !!item.image);
    for (let i = 0; i < list.length; i++) {
      list[i] = null;
    }
    setList([...list]);
    for (let i = 0; i < cards.length; i++) {
      let c = cards[i];
      if (c === null) {
        cards[i] = cs.shift();
      }
    }
    console.log('ns', cards, cs);
    setCards([...cards]);
  };
  const giveUp = () => {
    console.log('round', round, nowBigRound.length);
    if (round >= nowBigRound.length - 1) {
      ToastAndroid.show('关卡已经结束', 1);
      return;
    }
    nextRound();
  };

  const noAnswer = () => {};

  return (
    <View style={styles.container}>
      <View style={styles.top}>
        <Text>
          {round + 1}/{nowBigRound.length}
        </Text>
        <View style={styles.cutdown}>
          <Image
            source={require('./images/24/clock.png')}
            style={{width: 30, height: 30}}
          />
          <Text>倒计时:{count}秒</Text>
        </View>
      </View>
      <View style={{flex: 1, marginTop: 20}}>
        <View style={{flexDirection: 'row', gap: 10}}>
          {list.map((item, i) => {
            return item == null ? (
              <View key={i} style={styles.emptyCard}></View>
            ) : typeof item === 'string' ? (
              <View key={i} style={styles.cardItem}>
                <Text style={{fontSize: 40, color: '#000'}}>{item}</Text>
              </View>
            ) : (
              <Image
                key={i}
                source={item.image}
                resizeMode={'contain'}
                style={{width: cardWidth, height: cardHeight}}
              />
            );
          })}
        </View>
        <View
          style={{
            flexDirection: 'row',
            gap: 20,
            justifyContent: 'center',
            marginTop: 10,
          }}>
          {cards.map((item, i) => {
            return item == null ? (
              <View
                key={i}
                style={{
                  width: cardWidth,
                  height: cardHeight,
                  borderWidth: 0.5,
                  borderColor: '#8888888',
                  borderRadius: 6,
                }}></View>
            ) : (
              <TouchableOpacity
                key={i}
                onPress={() => {
                  clickCard(item, i);
                }}>
                <Image
                  key={i}
                  source={item.image}
                  resizeMode={'contain'}
                  style={{width: cardWidth, height: cardHeight}}
                />
              </TouchableOpacity>
            );
          })}
        </View>
      </View>
      <View
        style={{
          flexDirection: 'row',
          alignItems: 'center',
          gap: 10,
          justifyContent: 'center',
        }}>
        <Text
          style={styles.op}
          onPress={() => {
            addOp('+');
          }}>
          +
        </Text>
        <Text
          style={styles.op}
          onPress={() => {
            addOp('-');
          }}>
          -
        </Text>
        <Text
          style={styles.op}
          onPress={() => {
            addOp('*');
          }}>
          *
        </Text>
        <Text
          style={styles.op}
          onPress={() => {
            addOp('/');
          }}>
          /
        </Text>
        <Text style={styles.op}>(</Text>
        <Text style={styles.op}>)</Text>
        <Text style={styles.op}>+</Text>
        <TouchableOpacity
          onPress={() => {
            noAnswer();
          }}>
          <Image
            source={require('./images/24/wujie.png')}
            resizeMode={'contain'}
            style={{width: 80, height: 40}}
          />
        </TouchableOpacity>
        <TouchableOpacity
          onPress={() => {
            giveUp();
          }}>
          <Image
            source={require('./images/24/fangqi.png')}
            resizeMode={'contain'}
            style={{width: 80, height: 40}}
          />
        </TouchableOpacity>
        <TouchableOpacity
          onPress={() => {
            clear();
          }}>
          <Image
            source={require('./images/24/qingkong.png')}
            resizeMode={'contain'}
            style={{width: 80, height: 40}}
          />
        </TouchableOpacity>
        <TouchableOpacity
          onPress={() => {
            submit();
          }}>
          <Image
            source={require('./images/24/tijiao.png')}
            resizeMode={'contain'}
            style={{width: 80, height: 40}}
          />
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
    height: sheight,
    flexDirection: 'column',
    backgroundColor: '#ffecc9',
  },
  top: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  cutdown: {flexDirection: 'row', alignItems: 'center', gap: 10},
  emptyCard: {
    width: cardWidth,
    height: cardHeight,
    borderWidth: 0.5,
    borderColor: '#aaaaaa',
    backgroundColor: '#fff',
    borderRadius: 6,
  },
  cardItem: {
    width: cardWidth,
    height: cardHeight,
    borderWidth: 0.5,
    borderColor: '#aaaaaa',
    borderRadius: 6,
    alignItems: 'center',
    justifyContent: 'center',
  },
  op: {
    width: 30,
    height: 40,
    lineHeight: 40,
    textAlign: 'center',
    backgroundColor: '#fff',
  },
  card: {
    borderWidth: 1,
    borderColor: '#333333',
    width: '15%',
    height: '30%',
  },
});
